from django.db import transaction
from django.shortcuts import render, redirect

# Create your views here.
from django.views import View

from ihome.settings.dev import BASE_URL

import json
from datetime import datetime

from django.core.paginator import Paginator, EmptyPage
from django.utils import timezone

from django import http
from django.shortcuts import redirect
from django.views import View
from addresses.models import Area
from houses.models import House, Facility, HouseImage
from ihome.settings.dev import BASE_URL
from ihome.utils.fdfs.fastdfs_storage import FDFSStorage
from ihome.utils.response_code import RET
from ihome.utils.views import LandlordMixin

# 返回html页面
class HtmlView(View):
    def get(self, request):

        params = request.GET
        params_str = ''
        if params:
            for item in params.items():
                params_str =params_str + '&%s=%s' %(item[0],item[1])

        path_str = params_str.replace('&','?',1)

        path = request.path + path_str
        return redirect(BASE_URL + path)

        # print(path, '------------------------------')
# http://127.0.0.1:8000/detail.html?id=1
# ----> http://127.0.0.1:8000/static/html/detail.html?id=1




# 房东与登陆验证,新增房源
class NewHouseView(LandlordMixin,View):
# class NewHouseView(View):
    def post(self, request):
        data = json.loads(request.body.decode())

        user_id = request.user.id
        # user_id = '1'
        title = data.get('title')
        price = data.get('price')
        area_id = data.get('area_id')
        address = data.get('address')
        room_count = data.get('room_count')
        acreage = data.get('acreage')
        unit = data.get('unit')
        capacity = data.get('capacity')
        beds = data.get('beds')
        deposit = data.get('deposit')
        min_days = data.get('min_days')
        max_days = data.get('max_days')
        facility = data.get('facility')

        if not all(['title', 'price', 'area_id', 'address', 'room_count', 'acreage', 'unit',
                    'capacity', 'beds', 'deposit', 'min_days', 'max_days', 'facility']):
            return http.JsonResponse({'errmsg': '缺少必传参数',
                                      'errno': RET.PARAMERR})
        if not Area.objects.filter(id=area_id):
            return http.JsonResponse({'errmsg': '该区域不存在',
                                      'errno': RET.PARAMERR})

        with transaction.atomic():
            try:
                house = House.objects.create(
                    user_id=user_id,
                    title=title,
                    price=price,
                    area_id=area_id,
                    address=address,
                    room_count=room_count,
                    acreage=acreage,
                    unit=unit,
                    capacity=capacity,
                    beds=beds,
                    deposit=deposit,
                    min_days=min_days,
                    max_days=max_days)
                # facility_list = eval(facility)  # 转化为list
                facility_obj_list = Facility.objects.filter(id__in=facility)
                # ManyToManyField字段更新
                house.facilities.add(*facility_obj_list)
                house.save()
            except Exception:
                return http.JsonResponse({'errmsg': '保存失败',
                                      'errno': RET.SERVERERR})

        return http.JsonResponse({'errmsg': 'OK',
                                  'errno': RET.OK,
                                  "data":{
                                      'house_id': house.id
                                  }
                                  })



# 保存房源图片,   /api/v1.0/houses/(?P<house_id>\d+)/images/
class HouseImageView(LandlordMixin, View):
    def post(self, request, house_id):

        image_obj = request.FILES.get('house_image')

        if not image_obj:
            return http.JsonResponse({'errmsg': '无图片',
                                      'errno': RET.NODATA})
        try:
            house = House.objects.get(id=house_id)
        except House.DoesNotExist:
            return http.JsonResponse({'errmsg': '无房屋',
                                      'errno': RET.NODATA})

        storage = FDFSStorage()
        # fdfs 中的文件名是由 fdfs 生成的, 所以不可能冲突,此处不校验
        file_id = storage._save(image_obj.name, image_obj)
        image_url = storage.url(file_id)

        with transaction.atomic():
            try:
                if not house.index_image_url:
                    house.index_image_url = image_url
                    house.save()
                HouseImage.objects.create(house_id=house_id, url=image_url)
            except Exception:
                return http.JsonResponse({'errmsg': '保存失败',
                                          'errno': RET.DBERR})

        return http.JsonResponse({'errno': RET.OK,
                                  'errmsg': "OK",
                                  'data': {"url": image_url}
                                  })


# 首页房源推荐API   /api/v1.0/houses/index/
class HouseIndexView(View):
    def get(self, request):
        houses = House.objects.all()
        data = []
        for house in houses:
            data.append({'house_id': house.id,
                         'img_url': house.index_image_url,
                         'title': house.title})
        contents = {
            'data': data,
            'errmsg': 'OK',
            'errno': RET.OK
        }

        return http.JsonResponse(contents)


# 首页房源搜索API  /api/v1.0/houses/search/
class HouseSearchView(View):
    def get(self, request):
        area_id = request.GET.get('aid')
        start_day = request.GET.get('sd')
        end_day = request.GET.get('ed')
        sort_param = request.GET.get('sk')
        page_num = request.GET.get('p', '1')

        if not all(['area', 'start_day', 'end_day', 'sort_param']):
            return http.JsonResponse({'errmsg': '缺少必传参数',
                                      'errno': RET.PARAMERR})
        if not Area.objects.filter(id=area_id):
            return http.JsonResponse({'errmsg': '该区域不存在',
                                      'errno': RET.PARAMERR})
        if sort_param not in ['booking', 'price-inc', 'price-des','new']:
            return http.JsonResponse({'errmsg': '排序方式不正确',
                                      'errno': RET.PARAMERR})
        # if not isinstance(page_num, int):
        #     return http.JsonResponse({'errmsg': '参数格式不正确',
        #                               'errno': RET.PARAMERR})
        # 今天日期　xxx-xxx-xxx
        t = timezone.now().date()
        try:
            start_date = datetime.strptime(start_day, '%Y-%m-%d').date()
            end_date = datetime.strptime(end_day, '%Y-%m-%d').date()
            if start_date < t or end_date < start_date:
                return http.JsonResponse({'errmsg': '日期有误',
                                          'errno': RET.PARAMERR})
        except Exception:
            return http.JsonResponse({'errmsg': '日期有误',
                                      'errno': RET.PARAMERR})

        if sort_param == 'booking':
            sort_kind = '-order_count'
        elif sort_param == 'price-inc':
            sort_kind = 'price'
        elif sort_param == 'new':
            sort_kind = '-create_time'
        else:
            sort_kind = '-price'

        # 居住日期
        live_day = (end_date - start_date).days + 1

        houses = House.objects.filter(area_id=area_id,
                                      min_days__lte=live_day,
                                      max_days__gte=live_day).order_by(sort_kind)

        try:
            page_num = int(page_num)
            paginator = Paginator(houses, 2)
            page_houses = paginator.page(page_num)
            total_page = paginator.num_pages
        except EmptyPage:
            return http.HttpResponseNotFound('房屋信息不存在')

        houses = []
        for house in page_houses:
            ctime = house.create_time
            house = {'address': house.address,
                     'area_name': house.area.name,
                     'ctime': '%d-%02d-%02d' % (ctime.year, ctime.month, ctime.day),
                     'house_id': house.id,
                     'img_url': house.index_image_url,
                     'order_count': 17,
                     'price': house.price,
                     'room_count': house.room_count,
                     'title': house.title,
                     'user_avatar': house.user.avatar_url
                     }
            houses.append(house)

        data = {'houses': houses,
                'total_page': total_page}
        contents = {
            'data': data,
            'errmsg': '请求成功',
            'errno': RET.OK
        }

        return http.JsonResponse(contents)


class UserHouseView(LandlordMixin, View):
    """我的房源"""

    def get(self, request):
        houses = House.objects.filter(user__id_card = request.user.id_card)
        house_list = []
        for house in houses:
            address = house.address
            t = house.create_time
            ctime = '%d-%02d-%02d  %02d:%02d:%02d' %(t.year,t.month,t.day,t.hour,t.minute,t.second)

            dict = {
                'address': address,
                'area_name': house.area.name,
                'ctime': ctime,
                'house_id': house.id,
                'img_url': house.index_image_url,
                'order_count': house.order_count,
                'price': house.price,
                'room_count': house.room_count,
                'title': house.title,
                'user_avatar': house.user.avatar_url
            }

            house_list.append(dict)

        context = {
            'data': house_list,
            'errmsg': 'OK',
            'errno': RET.OK
        }

        return http.JsonResponse(context)


class HouseDetailView(View):
    """房源详情"""

    def get(self, request, house_id):
        user_id = request.user.id
        if not user_id:
            user_id = -1
        try:

            house = House.objects.get(id=house_id)

        except House.DoesNotExist:

            return http.HttpResponseNotFound('页面找不到')

        orders = house.order_set.filter(comment__isnull=False,status = 'COMPLETE').order_by('-update_time')
        comments = []
        for order in orders:
            t = order.update_time
            ctime = '%d-%02d-%02d  %02d:%02d:%02d' %(t.year,t.month,t.day,t.hour,t.minute,t.second)
            comments.append({
                        'comment': order.comment,
                        'ctime': ctime,
                        'user_name': house.user.username
            })

        facilities_list = []
        facilities = house.facilities.all()
        for facility in facilities:
            facilities_list.append(facility.id)

        images = house.houseimage_set.filter(url__isnull = False)
        img_urls = []
        for image in images:
            img_urls.append(image.url)

        context = {
            'data': {
                'house': {
                    'acreage': house.acreage,
                    'address': house.address,
                    'beds': house.beds,
                    'capacity': house.capacity,
                    'comments': comments,
                    'deposit': house.deposit,
                    'facilities': facilities_list,
                    'hid': house.id,
                    'img_urls': img_urls,
                    'max_days': house.max_days,
                    'min_days': house.min_days,
                    'price': house.price,
                    'room_count': house.room_count,
                    'title': house.title,
                    'unit': house.unit,
                    'user_avatar': house.user.avatar_url,
                    'user_id': house.user.id,
                    'user_name': house.user.username
                },
                'user_id': user_id,
            },
            'errmsg': 'OK',
            'errno': RET.OK
        }

        return http.JsonResponse(context)


